/**
 * 收到请求时，把网页相应回去
 * http://localhost:8081/
 * 将index.html相应到前端
 */

const http = require("http");
const url = require("url");
const fs = require("fs");
const path = require("path");
const https = require("https");
const cheerio = require("cheerio");

var reqUrl = "https://maoyan.com/films?showType=3";
var movieList = [];

http.createServer((req,res)=>{
    //req请求对象，res响应对象
    var urlObj = url.parse(req.url);
    var pathname = urlObj.pathname;
    if(pathname == "/"){ //将index.html相应到浏览器上
        var filePath = path.join(__dirname, "/index.html");
        fs.readFile(filePath, (err,data)=>{ //data是buffer数据
            if(err){ 
                console.log(err) 
            }
            else{
                res.writeHead(200,{"Content-Type":"text/html;charset=utf-8"});
                res.write(data);
                res.end()
            }
            
        })
    }
    else if(pathname == "/getlist"){ //开始爬虫
        https.get(reqUrl,(resObj)=>{ //resObj是可读流
            var htmlStr = ""
            resObj.on("data",(chunk)=>{
                htmlStr += chunk;
            })
            resObj.on("end", ()=>{
                // console.log(htmlStr); //得到index.html代码
                var $ = cheerio.load(htmlStr);
                $(".movie-item-title a").each((i,el)=>{
                    var movieName = $(el).text();
                    var movieId = $(el).attr("data-val"); //获取movieID
                    movieId = movieId.slice(movieId.indexOf(":")+1, -1); //获取movieId后的数字
                    //获取评分
                    var num1 = $(el).parent().next().children(".integer").text();
                    var num2 = $(el).parent().next().children(".fraction").text();
                    var rate = num1+num2; 
                    var movieObj = {movieId: movieId, movieName: movieName, movieRate: rate}
                    movieList.push(movieObj);
                })
                res.writeHead(200, {"Content-Type":"text/plain"});
                res.write(JSON.stringify(movieList));
                res.end();
            })
        })

    }

}).listen(8081);

console.log("server is listening 8081")